// caphook.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "caphook.h"
#include <stdio.h>

#pragma data_seg(".HOOKDATA")//Shared data among all instances.
HHOOK hook = NULL;
HWND hwnd = NULL;
unsigned char m_key = 'A';
unsigned char m_shift = 0;
unsigned char m_alt = 1;
unsigned char m_ctrl = 1;
#pragma data_seg()

#pragma comment(linker, "/SECTION:.HOOKDATA,RWS")//linker directive

HINSTANCE hinstance = NULL;

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
		case DLL_PROCESS_DETACH:
			break;
    }

	hinstance = (HINSTANCE)hModule;
	hook = NULL;

    return TRUE;
}


KEYDLL3_API void installhook(HWND h)
{
	hook = NULL;
	hwnd = h;
	hook = SetWindowsHookEx(WH_KEYBOARD,hookproc,hinstance,NULL);
	if(hook==NULL)
		MessageBoxA(NULL,"Unable to install hook","Error!",MB_OK);
}

KEYDLL3_API void removehook()
{
	UnhookWindowsHookEx(hook);
}

KEYDLL3_API LRESULT CALLBACK hookproc(int ncode,WPARAM wparam,LPARAM lparam)
{
	if(ncode>=0)
	{
		if (wparam == 27)
			PostMessage(hwnd,WM_USER+755,wparam,lparam);

		if (((lparam & 0x80000000) == 0) && (wparam == m_key)) {
			if ((!m_shift || (GetAsyncKeyState(VK_SHIFT) & 0xf000)) &&
				(!m_alt || (GetAsyncKeyState(VK_MENU) & 0xf000)) &&
				(!m_ctrl || (GetAsyncKeyState(VK_CONTROL)) & 0xf000)) {
					PostMessage(hwnd,WM_USER+755,wparam,lparam);
					return true;
			}
		}
	}
	return ( CallNextHookEx(hook,ncode,wparam,lparam) );//pass control to next hook in the hook chain.
}

KEYDLL3_API void define_capkey(unsigned char key, unsigned char alt, unsigned char ctrl, unsigned char shift)
{
	m_key = key;
	m_shift = shift;
	m_alt = alt;
	m_ctrl = ctrl;	
}